package com.example.myys.viewModel.settingModel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myys.Constants
import com.example.myys.data.entity.SettingLink
import com.example.myys.data.repository.MovieRepository
import com.example.myys.data.repository.SettingLinkRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class SettingViewModel: ViewModel() {
    private val _ysState: MutableStateFlow<List<SettingLink>> =
        MutableStateFlow(value = arrayListOf())
    val ysState: StateFlow<List<SettingLink>>
        get() = _ysState

    private val _xsState: MutableStateFlow<List<SettingLink>> =
        MutableStateFlow(value = arrayListOf())
    val xsState: StateFlow<List<SettingLink>>
        get() = _xsState

    private val _mhState: MutableStateFlow<List<SettingLink>> =
        MutableStateFlow(value = arrayListOf())
    val mhState: StateFlow<List<SettingLink>>
        get() = _mhState
    private val _systemState: MutableStateFlow<List<SettingLink>> =
        MutableStateFlow(value = arrayListOf())
    val systemState: StateFlow<List<SettingLink>>
        get() = _systemState

    fun getTypeList(type: String) {
        viewModelScope.launch(Dispatchers.IO) {
            when (type) {
                Constants.YS -> _ysState.value = SettingLinkRepository.getSettingByType(type)
                Constants.XS -> _xsState.value = SettingLinkRepository.getSettingByType(type)
                Constants.MH -> _mhState.value = SettingLinkRepository.getSettingByType(type)
                Constants.SYSTEM -> _systemState.value =
                    SettingLinkRepository.getSettingByType(type)
            }
        }
    }

    fun saveSetting(settingLink: SettingLink) {
        viewModelScope.launch(Dispatchers.IO) {
            SettingLinkRepository.saveSetting(settingLink)
            getTypeList(settingLink.type)
        }
    }

    fun updateIsChecked(type: String, settingLink: SettingLink) {
        viewModelScope.launch(Dispatchers.IO) {
            settingLink.isChecked = 1
            SettingLinkRepository.updateIsChecked(type, settingLink)
            getTypeList(type)
            when (type) {
                Constants.YS -> MovieRepository.initObject()
                Constants.XS -> {}
                Constants.MH -> {}
            }
        }
    }

    fun deleteSeting(type: String, settingLink: SettingLink) {
        viewModelScope.launch(Dispatchers.IO) {
            SettingLinkRepository.deleteSetting(settingLink)
            getTypeList(type)
        }
    }

    init {
        getTypeList(Constants.YS)
        getTypeList(Constants.XS)
        getTypeList(Constants.MH)
        getTypeList(Constants.SYSTEM)
    }
}